const express = require('express')
const router = express.Router()
const userController = require('./controllers/user.js')
const sessionController = require('./controllers/session.js')
const topicController = require('./controllers/topic.js')
const commentController = require('./controllers/comment.js')
const newsController = require('./controllers/news.js')
const topicModel = require('./models/topic.js')

function checkLogin (req, res, next) {
	const {user} = req.session
	if ( ! user) {
		return res.status(401).json({
			error : 'Unauthorized'
		})
	}
	next()
}

async function checkTopic (req, res, next) {
	try {
		const {id} = req.params
		const topic = await topicModel.getTopic(id)
		// 如果资源不存在
		if ( ! topic) {
			return res.status(404).json({
				error : 'Topic not Found'
			})
		}
		// 如果话题不属于作者自己
		if (topic.user_id !== req.session.user.id) {
			return res.status(400).json({
				error : 'Action Invalid'
			})
		}
		next()
	} catch(err) {
		next(err)
	}
}

router
	.get('/users', userController.get)
	.post('/users', userController.create)
	.patch('/users/:id', userController.update)
	.delete('/users/:id', userController.destroy)

router
	.get('/topics', topicController.list)
	.get('/topics/:id', topicController.one)
	.post('/topics', checkLogin, topicController.create)
	.patch('/topics/:id', checkLogin, checkTopic, topicController.update)
	.delete('/topics/:id', checkLogin, checkTopic, topicController.delete)

router
	.get('/comments', commentController.list)
	.post('/comments', checkLogin, commentController.create)
	.patch('/comments', checkLogin, commentController.update)
	.delete('/comments', checkLogin, commentController.delete)

router
	.get('/session', sessionController.get)
	.post('/session', sessionController.create)
	.delete('/session', sessionController.destroy)

router
	.get('/lunbo', newsController.lunbo)

module.exports = router